import { defineStore } from 'pinia'
import { ref, watch } from 'vue'
import { Store } from '@tauri-apps/plugin-store'
import { message } from '@tauri-apps/plugin-dialog'
import { fetch } from '@tauri-apps/plugin-http'

export interface ChatMessage {
  role: 'user' | 'assistant' | 'system'
  content: string
  timestamp: number
  model?: string
}

export interface ModelConfig {
  id: string
  name: string
  model: string
  apiKey: string
  baseUrl: string
  temperature: number
  maxTokens: number
  topP: number
  frequencyPenalty: number
  presencePenalty: number
  systemPrompt: string
  enableStreaming: boolean
}

export interface ChatSession {
  id: string
  title: string
  messages: ChatMessage[]
  createdAt: number
  updatedAt: number
}

interface StoreData {
  sessions: ChatSession[]
  currentSessionId: string | null
  modelConfigs: ModelConfig[]
  currentModelConfigId: string | null
  documents: Array<{ id: string; name: string; content: string }>
}

// 创建持久化存储
const defaultConfig: StoreData = {
  sessions: [],
  currentSessionId: null,
  modelConfigs: [{
    id: 'deepseek-chat',
    name: 'deepseek',
    model: 'deepseek-chat',
    apiKey: '',
    baseUrl: 'https://api.deepseek.com',
    temperature: 0.7,
    maxTokens: 5000,
    topP: 1,
    frequencyPenalty: 0,
    presencePenalty: 0,
    systemPrompt: '你是一个有用的AI助手。',
    enableStreaming: false,
  },{
    id: 'deepseek-v3',
    name: 'aliyun-deepseek',
    model: 'deepseek-v3',
    apiKey: '',
    baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
    temperature: 0.7,
    maxTokens: 5000,
    topP: 1,
    frequencyPenalty: 0,
    presencePenalty: 0,
    systemPrompt: '你是一个有用的AI助手。',
    enableStreaming: false,
  },{
    id: 'gpt-3.5-turbo',
    name: 'GPT-3.5 Turbo',
    model: 'gpt-3.5-turbo',
    apiKey: '',
    baseUrl: 'https://api.openai.com/v1/chat/completions',
    temperature: 0.7,
    maxTokens: 2000,
    topP: 1,
    frequencyPenalty: 0,
    presencePenalty: 0,
    systemPrompt: '你是一个有用的AI助手。',
    enableStreaming: true,
  }, {
    id: 'gpt-4',
    name: 'GPT-4',
    model: 'gpt-4',
    apiKey: '',
    baseUrl: 'https://api.openai.com/v1/chat/completions',
    temperature: 0.7,
    maxTokens: 2000,
    topP: 1,
    frequencyPenalty: 0,
    presencePenalty: 0,
    systemPrompt: '你是一个有用的AI助手。',
    enableStreaming: true,
  }, {
    id: 'claude-3-opus',
    name: 'Claude 3 Opus',
    model: 'claude-3-opus-20240229',
    apiKey: '',
    baseUrl: 'https://api.anthropic.com/v1/messages',
    temperature: 0.7,
    maxTokens: 4000,
    topP: 1,
    frequencyPenalty: 0,
    presencePenalty: 0,
    systemPrompt: '你是一个有用的AI助手。',
    enableStreaming: true,
  }, {
    id: 'claude-3-sonnet',
    name: 'Claude 3 Sonnet',
    model: 'claude-3-sonnet-20240229',
    apiKey: '',
    baseUrl: 'https://api.anthropic.com/v1/messages',
    temperature: 0.7,
    maxTokens: 4000,
    topP: 1,
    frequencyPenalty: 0,
    presencePenalty: 0,
    systemPrompt: '你是一个有用的AI助手。',
    enableStreaming: true,
  }],
  currentModelConfigId: 'gpt-3.5-turbo',
  documents: []
}

export interface ModelPreset {
  name: string
  baseUrl: string
  maxTokens: number
}

export const useAIStore = defineStore('ai', () => {
  const sessions = ref<ChatSession[]>([])
  const currentSessionId = ref<string | null>(null)
  const modelConfigs = ref<ModelConfig[]>([])
  const currentModelConfigId = ref<string | null>(null)
  const isProcessing = ref(false)
  const isStreaming = ref(false)
  const abortController = ref<AbortController | null>(null)

  // 获取当前模型配置
  const getCurrentModelConfig = () => {
    return modelConfigs.value.find((c: ModelConfig) => c.id === currentModelConfigId.value) || modelConfigs.value[0]
  }

  // 添加模型配置
  const addModelConfig = (config: Omit<ModelConfig, 'id'>) => {
    const newConfig: ModelConfig = {
      ...config,
      id: Date.now().toString()
    }
    modelConfigs.value.push(newConfig)
    if (!currentModelConfigId.value) {
      currentModelConfigId.value = newConfig.id
    }
  }

  // 更新模型配置
  const updateModelConfig = (id: string, config: Partial<ModelConfig>) => {
    const index = modelConfigs.value.findIndex(c => c.id === id)
    if (index !== -1) {
      modelConfigs.value[index] = {
        ...modelConfigs.value[index],
        ...config
      }
    }
  }

  // 删除模型配置
  const deleteModelConfig = (id: string) => {
    const index = modelConfigs.value.findIndex(c => c.id === id)
    if (index !== -1) {
      modelConfigs.value.splice(index, 1)
      if (currentModelConfigId.value === id) {
        currentModelConfigId.value = modelConfigs.value.length > 0 ? modelConfigs.value[0].id : null
      }
    }
  }

  // 初始化时从存储加载数据
  const initialize = async () => {
    try {
      const store = await Store.load('.config/ai-config.json')
      const data = await store.get<StoreData>('ai-config')
      if (data) {
        sessions.value = data.sessions
        currentSessionId.value = data.currentSessionId
        modelConfigs.value = data.modelConfigs
        currentModelConfigId.value = data.currentModelConfigId
      } else {
        modelConfigs.value = defaultConfig.modelConfigs
        currentModelConfigId.value = defaultConfig.currentModelConfigId
        await store.set('ai-config', defaultConfig)
        await store.save()
      }
    } catch (error) {
      console.error('加载配置失败:', error)
      await message('加载配置失败，将使用默认配置', { title: '错误' })
    }
  }

  // 监听数据变化并保存
  watch([sessions, currentSessionId, modelConfigs, currentModelConfigId], async () => {
    try {
      const store = await Store.load('.config/ai-config.json')
      await store.set('ai-config', {
        sessions: sessions.value,
        currentSessionId: currentSessionId.value,
        modelConfigs: modelConfigs.value,
        currentModelConfigId: currentModelConfigId.value
      })
      await store.save()
    } catch (error) {
      console.error('保存配置失败:', error)
    }
  }, { deep: true })

  const getCurrentSession = () => {
    return sessions.value.find(s => s.id === currentSessionId.value)
  }

  const createSession = () => {
    const session: ChatSession = {
      id: Date.now().toString(),
      title: '新对话',
      messages: [],
      createdAt: Date.now(),
      updatedAt: Date.now()
    }
    sessions.value.push(session)
    currentSessionId.value = session.id
    return session
  }

  const deleteSession = (id: string) => {
    const index = sessions.value.findIndex(s => s.id === id)
    if (index !== -1) {
      sessions.value.splice(index, 1)
      if (currentSessionId.value === id) {
        currentSessionId.value = sessions.value.length > 0 ? sessions.value[0].id : null
      }
    }
  }

  const updateSessionTitle = (id: string, title: string) => {
    const session = sessions.value.find(s => s.id === id)
    if (session) {
      session.title = title
      session.updatedAt = Date.now()
    }
  }

  const addMessage = (message: ChatMessage) => {
    const session = getCurrentSession()
    if (session) {
      // 创建新的消息对象，确保所有字段都被正确复制
      const newMessage = {
        role: message.role,
        content: message.content,
        timestamp: message.timestamp,
        model: message.model
      }
      
      // 使用数组解构来触发 Vue 的响应式更新
      session.messages = [...session.messages, newMessage]
      session.updatedAt = Date.now()
      
      // 如果是第一条消息，用它来更新会话标题
      if (session.messages.length === 1 && message.role === 'user') {
        const title = message.content.slice(0, 20) + (message.content.length > 20 ? '...' : '')
        session.title = title
      }
    }
  }

  const updateMessage = (sessionId: string, messageIndex: number, content: string) => {
    const session = sessions.value.find(s => s.id === sessionId)
    if (session && session.messages[messageIndex]) {
      // 创建新的消息数组
      const updatedMessages = [...session.messages]
      updatedMessages[messageIndex] = {
        ...updatedMessages[messageIndex],
        content
      }
      // 更新整个消息数组以触发响应式更新
      session.messages = updatedMessages
      session.updatedAt = Date.now()
    }
  }

  // 添加一个新的方法用于立即保存到存储
  const saveToStore = async () => {
    try {
      const store = await Store.load('.config/ai-config.json')
      await store.set('ai-config', {
        sessions: sessions.value,
        currentSessionId: currentSessionId.value,
        modelConfigs: modelConfigs.value,
        currentModelConfigId: currentModelConfigId.value
      })
      await store.save()
    } catch (error) {
      console.error('保存配置失败:', error)
    }
  }

  const stopGenerating = () => {
    if (abortController.value) {
      abortController.value.abort()
      abortController.value = null
      isProcessing.value = false
    }
  }

  const sendMessage = async (content: string): Promise<string> => {
    const currentConfig = getCurrentModelConfig()
    if (!currentConfig) {
      throw new Error('请先选择或添加模型配置')
    }

    if (!currentConfig.apiKey) {
      throw new Error('请先配置 API 密钥')
    }

    if (isProcessing.value) {
      throw new Error('正在处理上一条消息')
    }

    isProcessing.value = true
    // 创建新的中止控制器
    abortController.value = new AbortController()

    // 声明在 try-catch 块外，以便在 catch 中也能访问
    let session = getCurrentSession()
    let assistantIndex = -1

    try {
      if (!session) {
        throw new Error('未找到当前会话')
      }

      // 添加用户消息
      const userMessage: ChatMessage = {
        role: 'user',
        content,
        timestamp: Date.now()
      }
      addMessage(userMessage)

      // 准备上下文消息
      const systemMessage = currentConfig.systemPrompt ? {
        role: 'system' as const,
        content: currentConfig.systemPrompt
      } : null;

      // 获取最近的消息（不包括 system 消息）
      const recentMessages = session.messages
        .filter(msg => msg.role !== 'system')
        .slice(-10)
        .map(msg => ({
          role: msg.role,
          content: msg.content
        }));

      // 组合上下文消息，确保 system prompt 在最前面
      const contextMessages = systemMessage 
        ? [systemMessage, ...recentMessages]
        : recentMessages;

      // 添加一个空的助手消息
      const assistantMessage: ChatMessage = {
        role: 'assistant',
        content: '',
        timestamp: Date.now(),
        model: currentConfig.model
      }
      assistantIndex = session.messages.length
      addMessage(assistantMessage)

      // 调用 API
      const response = await fetch(`${currentConfig.baseUrl}/chat/completions`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${currentConfig.apiKey}`
        },
        signal: abortController.value.signal,  // 添加中止信号
        body: JSON.stringify({
          model: currentConfig.model,
          messages: contextMessages,
          temperature: Number(currentConfig.temperature),
          max_tokens: Number(currentConfig.maxTokens),
          top_p: Number(currentConfig.topP),
          frequency_penalty: Number(currentConfig.frequencyPenalty),
          presence_penalty: Number(currentConfig.presencePenalty),
          stream: false
        })
      })

      // 处理响应
      if (!response.ok) {
        const errorText = await response.text()
        let errorMessage = `API 请求失败: ${response.status}`
        try {
          const errorData = JSON.parse(errorText)
          errorMessage = errorData.error?.message || errorData.message || errorMessage
        } catch (e) {
          errorMessage = errorText || errorMessage
        }
        throw new Error(errorMessage)
      }

      const responseData = await response.json()
      let messageContent = ''

      // 根据不同的模型处理响应数据
      if (currentConfig.model.startsWith('gpt-')) {
        messageContent = responseData.choices[0]?.message?.content || ''
      } else if (currentConfig.model.startsWith('claude-')) {
        messageContent = responseData.content[0]?.text || ''
      } else {
        messageContent = responseData.choices?.[0]?.message?.content || 
                        responseData.content?.[0]?.text ||
                        responseData.content ||
                        responseData.text ||
                        ''
      }

      // 使用新的 updateMessage 函数更新消息内容
      updateMessage(session.id, assistantIndex, messageContent)

      // 保存会话
      await saveToStore()
      
      return messageContent
    } catch (error) {
      console.error('发送消息失败:', error)
      // 如果是中止错误，不更新消息内容
      if (error === 'Request canceled' || (error instanceof Error && (error.name === 'AbortError' || error.message === 'Request canceled'))) {
        // 不删除消息，保持内容为空
        throw error // 继续抛出 AbortError，让视图层处理
      }
      // 如果是其他错误，删除助手的空消息
      if (session && assistantIndex !== -1) {
        session.messages.splice(assistantIndex, 1)
        await saveToStore()
      }
      throw error
    } finally {
      isProcessing.value = false
      abortController.value = null
    }
  }

  // 验证配置
  const validateConfig = async (config: ModelConfig) => {
    try {
      const response = await fetch(`${config.baseUrl}/chat/completions`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${config.apiKey}`
        },
        mode: 'cors',
        // connectTimeout: 3000,
        body: JSON.stringify({
          model: config.model,
          messages: [{ role: 'user', content: 'Hello' }],
          temperature: Number(config.temperature),
          max_tokens: Number(config.maxTokens),
          top_p: Number(config.topP),
          frequency_penalty: Number(config.frequencyPenalty),
          presence_penalty: Number(config.presencePenalty),
          stream: false
        })
      })
      console.log(response)

      if (!response.ok) {
        const errorText = await response.text()
        let errorMessage = `HTTP error! status: ${response.status}`
        try {
          const errorData = JSON.parse(errorText)
          errorMessage = errorData.error?.message || errorData.message || errorMessage
        } catch (e) {
          errorMessage = errorText || errorMessage
        }
        throw new Error(errorMessage)
      }

      const responseText = await response.text()
      if (!responseText) {
        throw new Error('API返回了空响应')
      }

      try {
        JSON.parse(responseText) // 验证响应是否为有效的 JSON
        return true
      } catch (e) {
        throw new Error('API返回了无效的 JSON 响应')
      }
    } catch (error) {
      console.error('验证配置失败:', error)
      throw error instanceof Error ? error : new Error('验证失败')
    }
  }

  // 修改获取模型列表的方法
  const fetchModelList = async (config: ModelConfig): Promise<string[]> => {
    try {
      const response = await fetch(`${config.baseUrl}/models`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${config.apiKey}`
        }
      })

      if (!response.ok) {
        throw new Error('获取模型列表失败')
      }

      const data = await response.json()
      // 尝试从响应中提取模型列表
      if (Array.isArray(data.data)) {
        return data.data
          .filter((model: any) => model.id || typeof model === 'string')
          .map((model: any) => model.id || model)
      } else if (Array.isArray(data)) {
        return data.map((model: any) => model.id || model)
      }
      return []
    } catch (error) {
      console.error('获取模型列表失败:', error)
      throw error
    }
  }

  // 添加获取模型列表的方法
  const getModelList = async (configId: string) => {
    const config = modelConfigs.value.find(c => c.id === configId)
    if (!config) {
      throw new Error('未找到配置')
    }
    return await fetchModelList(config)
  }

  // 初始化存储
  initialize()

  return {
    sessions,
    currentSessionId,
    modelConfigs,
    currentModelConfigId,
    isProcessing,
    isStreaming,
    getCurrentSession,
    getCurrentModelConfig,
    addModelConfig,
    updateModelConfig,
    deleteModelConfig,
    createSession,
    deleteSession,
    updateSessionTitle,
    addMessage,
    sendMessage,
    validateConfig,
    getModelList,  // 导出新方法
    stopGenerating,  // 导出停止方法
  }
}) 